#include <all.H>

int16_t vol_pwm_num;

void set_vol(uint8_t ch, float vol) // 2808 1V   28280 10V
{
	 uint16_t x;
	 uint8_t mode = 0;
	 float vol_num;

	adc_init();

	P_SW2 = 0X80;
	if (vol < 0)
	{
		vol = (-vol) * 100;
		mode = 1;
	}
	else
		vol *= 100;

	if (vol > 1000)
		vol = 1000;

	x = vol;

	x *= 29.257142;

	vol_pwm_num = x;

	vol_io = 1;
	if (ch == 1)
	{
		PWMA_CCR1 = x;
		PWMA_CCER1 |= 0x01; // 01 pwm1  10  pwm2
		PWMA_ENO |= 0X01;	// 01 pwm1  04  pwm2
		f1_io = 1;
		f2_io = 0;
		if (mode)
		{
			f1_up = 0;
			f1_down = 1;
		}
		else
		{
			f1_down = 0;
			f1_up = 1;
		}
		delay(10);
		while (1)
		{
			vol_num = get_vol();
			if (vol_num < 0)
				vol_num = -vol_num;
			if ((vol_num * 100) >= vol)
				break;
			else
				x += 5;
			PWMA_CCR1 = x;
			delay(10);
		}
	}
	else if (ch == 2)
	{
		PWMA_CCR2 = x;
		PWMA_CCER1 |= 0x10; // 01 pwm1  10  pwm2
		PWMA_ENO |= 0X04;	// 01 pwm1  04  pwm2
		f2_io = 1;
		f1_io = 0;
		if (mode)
		{
			f2_up = 0;
			f2_down = 1;
		}
		else
		{
			f2_down = 0;
			f2_up = 1;
		}
		delay(10);
		while (1)
		{

			vol_num = get_vol();

			if (vol_num < 0)
				vol_num = -vol_num;

			if ((vol_num * 100) >= vol)
				break;
			else
				x += 5;
			PWMA_CCR2 = x;
			delay(10);
		}
	}
	PWMA_BKR = 0X80; // 0x80 EN
	PWMA_CR1 = 1;	 // 1 start
	P_SW2 = 0X00;
	vol_io = 0;
	f1_io = 0;
	f2_io = 0;
}

void set_pwm_num(uint8_t ch, uint16_t num)
{

	P_SW2 = 0X80;

	if (ch == 1)
	{
		PWMA_CCR1 = num;
		PWMA_CCER1 |= 0x01; // 01 pwm1  10  pwm2
		PWMA_ENO |= 0X01;	// 01 pwm1  04  pwm2
	}
	else if (ch == 2)
	{
		PWMA_CCR2 = num;
		PWMA_CCER1 |= 0x10; // 01 pwm1  10  pwm2
		PWMA_ENO |= 0X04;	// 01 pwm1  04  pwm2
	}
	PWMA_BKR = 0X80; // 0x80 EN
	PWMA_CR1 = 1;	 // 1 start
	P_SW2 = 0X00;
}

void pwm_init()
{
	P_SW2 = 0X80;
	PWMA_PS |= 0XA;
	PWMA_PSCR = 0;	   // 分频
	PWMA_CCER1 = 0;	   // 清零
	PWMA_CCMR1 = 0X60; // 使能
	PWMA_CCMR2 = 0X60; //  使能
	PWMA_ARR = 32767;  // 周期
	P_SW2 = 0X00;
	set_vol(1, 0);
	set_vol(2, 0);
}
